範例一:從1數到10
in後面加可迭代物件
range(1,11):包含1不包含11
for x in range(1,11):
print(x)
1
2
3
4
5
6
7
8
9
10
範例二:從10讀到11並說happy new year!
for x in reversed(range(1,11)):
print(x)
print("happy new year!")
10
9
8
7
6
5
4
3
2
1
happy new year!
範例三:跳過信用卡卡號dash
continue:跳過特定字串
credit_card ="1234-5678-9567-4671"
for x in credit_card:
if x == '-':
continue
else:
print(x)
1
2
3
4
5
6
7
8
9
5
6
7
4
6
7
1
範例四:終止繼續顯示迭代字串
credit_card ="1234-5678-9567-4671"
for x in credit_card:
if x == '9':
break
else:
print(x)
1
2
3
4
-
5
6
7
8
-
範例五:迭代字典
key:鍵,value:值
1.只迭代鍵
my_dictionary = {"a":1,"b":2,"c":3}
for x in my_dictionary:
print(x)
a
b
c
2.迭代鍵和值
my_dictionary = {"a":1,"b":2,"c":3}
for key, value in my_dictionary.items():
print("key:", key)
print("value:",value)
key: a
value: 1
key: b
value: 2
key: c
value: 3